package lol.clann.minecraft.springboot.plugin.bukkit.command;

import com.google.common.base.Joiner;
import lombok.Getter;
import lombok.ToString;

import java.util.*;

/**
 *
 * @author pyz
 * @date 2019/5/4 7:15 PM
 */
@Getter
@ToString
public class CommandContext {
    private static final Joiner spaceJoiner = Joiner.on(" ");
    private String command;
    /**
     * --xxx=yyy
     */
    private Map<String, String> falgMap = new HashMap<>();
    private String[] args;
    private String[] origin;
    public static CommandContext parse(String command, String[] args) {
        CommandContext context = new CommandContext();
        context.resolve(command, args == null ? null : new ArrayList(Arrays.asList(args)));
        context.origin = args;
        return context;
    }

    private void resolve(String command, List<String> args) {
        this.command = command;
        if (args == null || args.isEmpty()) {
            this.args = new String[0];
            return;
        }
        args = resolve(spaceJoiner.join(args));
        List<String> list = new ArrayList<>();
        int index = 0;
        while (index < args.size()) {
            String arg = args.get(index++);
            if (arg.startsWith("--") && arg.length() >= 3) {
                String flag;
                String value;
                int eqIndex = arg.indexOf('=');
                if (eqIndex > 0) {
                    flag = arg.substring(2, eqIndex);
                    if (eqIndex < arg.length() - 1) {
                        value = arg.substring(eqIndex + 1);
                    } else {
                        value = "";
                    }
                } else {
                    flag = arg.substring(2);
                    value = "";
                }
                falgMap.put(flag, value);
            } else {
                list.add(arg);
            }
        }
        this.args = list.toArray(new String[list.size()]);
    }

    private static List<String> resolve(String str) {
        List<String> args = new ArrayList<>();
        int index = 0;
        while ((index = readString(str, index, args)) < str.length()) {

        }
        return args;
    }

    private static int readString(String str, int startIndex, List<String> args) {
        StringBuilder sb = new StringBuilder();
        boolean quot = false;
        int index = startIndex;
        boolean start = false;
        while (true) {
            if (index >= str.length()) {
                if (quot) {
                    throw new RuntimeException("未闭合的引号,str=" + str);
                }
//              解析结束
                args.add(sb.toString());
                return index;
            }
            char c = str.charAt(index++);
            if (c == '\\') {
                start = true;
                if (index < str.length()) {
//                  转义

                    sb.append(str.charAt(index++));
                } else {
//                  非法转义
                    throw new RuntimeException("非法转义,index=" + index + ",str=" + str);
                }
            } else if (c == ' ') {
                if (!start) {
                    continue;
                }
                if (quot) {
//                  引号内的空格
                    sb.append(' ');
                } else {
//                  遇到空格,直接结束
                    args.add(sb.toString());
                    return index;
                }
            } else if (c == '"') {
                start = true;
                if (!quot) {
//                  引号开始
                    start = true;
                    quot = true;
                    continue;
                } else {
                    if (index < str.length()) {
//                      结束引号后面如果还有字符,就必须是空格
                        if (str.charAt(index) != ' ') {
                            throw new RuntimeException("未转义的引号,index=" + index + ",str=" + str);
                        } else {
//                          ok
                            args.add(sb.toString());
                            return index + 1;
                        }
                    } else {
//                      结束引号
                        args.add(sb.toString());
                        return index + 1;
                    }
                }
            } else {
                start = true;
                sb.append(c);
            }
        }
    }

    public static void main(String[] args) {
        String str = "dely    --player=\"000 000\"   xxxx\" asdsad\"  111 \"222\"    \" 333    \" \"444\" \" 555 \"";
        System.out.println(resolve(str));
        System.out.println(resolve("/morecommands dely 3 --player=Clann \"eco give\\ Clann 1000\""));
    }
}
